package com.janwen.spring.jdbc.template;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.janwen.spring.jdbc.datasource.AbstractJdbctemplate;

@Repository
public class JdbcTemplateCase extends AbstractJdbctemplate{

	static final Log logger = LogFactory.getLog(JdbcTemplateCase.class);
	
	public int[] batchUpdate(String[] sql){
		return getJdbcTemplate().batchUpdate(sql);
	}
	
	
	public int[] batchUpdate(String sql,
            BatchPreparedStatementSetter pss){
		
		return getJdbcTemplate().batchUpdate(sql, pss);
	}
	
	public int getFetchSize(String sql){
		getJdbcTemplate().queryForList(sql);
		return getJdbcTemplate().getFetchSize();
	}
	
	
	public Long getPrimaryKey(){
		 final String sql = "INSERT INTO stuff(name,age) VALUES(?,?)";
		KeyHolder holder = new GeneratedKeyHolder();
		getJdbcTemplate().update(
			    new PreparedStatementCreator() {
			    	@Override
			        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
			            PreparedStatement ps =
			                connection.prepareStatement(sql, new String[]{"id","name","age"});
			            ps.setString(1, "google");
			            ps.setLong(2, 1234);
			            return ps;
			        }
			    },
			    holder);
		Map<String,Object> keys = holder.getKeys();
		Iterator<Entry<String, Object>>  iterator = keys.entrySet().iterator();
		while(iterator.hasNext()){
			Entry<String, Object> entry = iterator.next();
			logger.info(entry.getKey() + " : " + entry.getValue());
		}
		return holder.getKey().longValue();
	}
	
}
